package com.tre.jdevtemplateboot.web.interceptor;

import com.tre.jdevtemplateboot.common.constant.SysConstantToken;
import com.tre.jdevtemplateboot.common.jwt.IJwtTokenManagerService;
import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.exception.business.SysUnAuthenticatedException;
import com.tre.jdevtemplateboot.exception.business.SysInvalidTokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JDev
 */
@Component
public class JDevRequestHeadJwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IJwtTokenManagerService jwtTokenManagerService;

    @Autowired
    PropertiesConfig propertiesVO;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws SysInvalidTokenException {

        String headerToken = HeadToken.getHeadToken(request, propertiesVO.getAuthHeaderKey(), propertiesVO.getAuthTypePrefix());
        if (!StringUtils.hasLength(headerToken)) {
            throw new SysUnAuthenticatedException();
        }
        headerToken = jwtTokenManagerService.updateToken(headerToken);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, headerToken);
        return true;
    }
}
